<template>
  <div class="wrap">
    <div class="search-wrap">
      <el-input
        v-model.trim="search.essaytitle"
        @keyup.enter="getEssayList"
        placeholder="模糊搜索短文标题"
        style="width: 220px; margin-right: 15px"
        size="default"
      />
      <el-select
        v-model="search.tagId"
        clearable
        style="width: 220px; margin-right: 15px"
        placeholder="选择书签"
        size="default"
      >
        <el-option
          v-for="item in allTagList"
          :key="item.id"
          :label="item.tagname"
          :value="item.id"
        />
      </el-select>
      <el-button
        class="search-class"
        size="default"
        type="primary"
        @click.stop="getEssayList"
        >查询</el-button
      >
    </div>
    <div class="table-header">
      <div>短文管理</div>
      <el-button class="add" size="default" type="primary" @click="addRow"
        >新增</el-button
      >
    </div>
    <el-table :data="essayList" style="width: 100%" :tbKey="tbKey">
      <!-- <el-table-column prop="id" label="id"> </el-table-column> -->
      <el-table-column
        prop="essaytitle"
        label="短文标题"
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column prop="user.username" label="来源" width="150">
      </el-table-column>
      <el-table-column prop="view_count" label="浏览" width="80">
      </el-table-column>
      <el-table-column prop="status" label="置顶" width="80">
        <template v-slot="scope">
          <img
            v-if="scope.row.status == 1"
            class="top"
            src="~src/assets/top.png"
            alt=""
          />
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column prop="watermarking" label="水印" width="80">
        <template v-slot="scope">
          <el-checkbox
            :key="scope.row.id"
            :checked="!!scope.row.watermarking"
            @change="watermarkingChange(scope.row, scope.$index)"
          ></el-checkbox>
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        label="创建时间"
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="updated_at"
        label="更新时间"
        width="150"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="拥有书签" width="200">
        <template v-slot="scope">
          {{ scope.row.tags.map((tag) => tag.tagname).join("、") }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="450">
        <template v-slot="scope">
          <el-button
            @click.stop="essayAddTag(scope.row)"
            type="primary"
            size="small"
          >
            添加书签
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click.stop="editorRow(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="warning"
            @click.stop="previewRow(scope.row)"
          >
            预览
          </el-button>
          <!-- <el-button
            size="small"
            type="primary"
            @click.stop="releaseRow(scope.row)"
          >
            发布
          </el-button> -->
          <el-button
            v-if="scope.row.status == 1"
            size="small"
            type="danger"
            @click="cancelPinned(scope.row.id)"
          >
            取消
          </el-button>
          <el-button v-else size="small" @click="pinned(scope.row.id)">
            置顶
          </el-button>
          <el-popconfirm
            title="确认要删除该列?"
            confirm-button-text="是"
            cancel-button-text="否"
            @confirm="deleteRow(scope.row)"
          >
            <template #reference>
              <el-button> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-footer">
      <el-pagination
        background
        @current-change="currentChange"
        :page-size="pagination.pageSize"
        layout="prev, pager, next"
        :total="pagination.total"
      />
    </div>

    <!-- 分配书签 -->
    <el-dialog
      v-model="dialogTagVisible"
      :close-on-click-modal="false"
      title="分配标签"
    >
      <el-form :model="form" label-position="top">
        <el-form-item label="书签（多选）" label-width="140px">
          <el-checkbox-group v-model="form.tags">
            <el-checkbox
              :label="tag.id"
              v-for="(tag, index) in allTagList"
              :key="index"
              >{{ tag.tagname }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogTagVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTag"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览短文 -->
     <PreviewContext ref="PreviewContextRef"  :previewTitle="essayPreviewTitle"  :previewContext="essayPreviewContext"></PreviewContext>
  </div>
</template>

<script>
import request from "utils/request";
import { ElMessage } from "element-plus";
import PreviewContext from "@/components/PreviewContext/PreviewContext"

export default {
  name: "NestAdminEssay",
 components:{
  PreviewContext
 },
  data() {
    return {
      tbKey: 0,
      dialogTagVisible: false,
      essayDrawer: false,
      essayPreviewTitle: "",
      essayPreviewContext: "",
      search: {
        essaytitle: "",
        tagId: "",
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      form: {
        id: "",
        essaytitle: "",
        tags: [],
      },
      essayList: [],
      allTagList: [],
    };
  },
  computed: {
    userId() {
      return this.$store.state.user.userInfo.id;
    },
  },
  async mounted() {
    await this.getEssayList();
    await this.getAllTagList();
  },
  methods: {
    async watermarkingChange(row, index) {
      let old = row.watermarking;
      let ret = await request.patch(`/essay/${row.id}`, {
        watermarking: !row.watermarking,
      });
      if (ret.code == 200) {
        row.watermarking = !row.watermarking;
      } else {
        row.watermarking = old;
      }
    },
    async getEssayList() {
      let ret = await request.get("/essay/list", {
        essaytitle: this.search.essaytitle,
        tagId: this.search.tagId,
        userId: this.userId,
        currentPage: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
      });
      if (ret.code == 200) {
        this.essayList = ret.data[0] || [];
        console.log("this.essayList", this.essayList);
        this.pagination.total = ret.data[1];
      }
    },
    async getAllTagList() {
      let ret = await request.get("tag/list", {
        tagname: "",
        userId: this.userId,
        currentPage: 1,
        pageSize: 1000,
      });
      if (ret.code == 200) {
        this.allTagList = ret.data[0] || [];
      }
    },
    async findEssaySelfTags(essayId) {
      let ret = await request.get(`/essay/hastags/${essayId}`);
      if (ret.code == 200) {
        this.form.tags = ret.data.map((item) => item.id) || [];
      }
    },
    async essayAddTag(row) {
      this.form.id = row.id;
      this.findEssaySelfTags(row.id);
      this.dialogTagVisible = true;
    },
    addRow() {
      this.$router.push({
        path: "/write-notes",
      });
    },
    editorRow(row) {
      this.$router.push({
        path: "/write-notes",
        query: {
          id: row.id,
        },
      });
    },
    previewRow(row) {
      this.essayPreviewTitle = row.essaytitle;
      this.essayPreviewContext = row.content;
      this.$refs.PreviewContextRef.openDrawer()
    },
    releaseRow(row) {
      window.open("/blog/essay.html?id=" + row.id, "__blank");
    },
    async deleteRow(row) {
      let ret = await request.delete(`/essay/${row.id}`, {});
      if (ret.code == 200) {
        ElMessage.success("删除成功");
        this.getEssayList();
      }
    },
    async currentChange(pageSize) {
      this.pagination.currentPage = pageSize;
      this.getEssayList();
    },
    async confirmTag() {
      let ret = await request.post("/essay/add/tag", {
        essayId: this.form.id,
        tagIds: this.form.tags,
      });
      if (ret.code == 200) {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.getEssayList();
        this.dialogTagVisible = false;
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
    async pinned(id) {
      let ret = await request.post(`/essay/pinned/${id}`, {
        status: 1,
      });
      if (ret.code == 200) {
        this.$message({
          message: "成功置顶",
          type: "success",
        });
        this.getEssayList();
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
    async cancelPinned(id) {
      let ret = await request.post(`/essay/pinned/${id}`, {
        status: 0,
      });
      if (ret.code == 200) {
        this.$message({
          message: "取消置顶",
          type: "success",
        });
        this.getEssayList();
      } else {
        this.$message({
          message: ret.message,
          type: "error",
        });
      }
    },
  },
};
</script>



<style lang="scss" scoped>
.wrap {
  .headPictureCol {
    width: 32px;
    height: 32px;
    overflow: hidden;
    border-radius: 50%;
  }
  .search-wrap {
    display: flex;
    margin-bottom: 15px;
    .search-class {
      // margin-left: 20px;
    }
  }
  .table-header {
    display: flex;
    line-height: 50px;
    padding: 0 10px;
    justify-content: space-between;
    align-items: center;
  }
  .pagination-footer {
    padding: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .top {
    width: 24px;
    text-align: center;
  }
}


</style>
